import { appStore } from '@/store/modules/app'
import { Product } from '@/types/model'
import { CartProduct, CartShop } from '@/types/store'
import { computed } from 'vue'

export interface CartInfo {
  count: number
  total: number
  price: number
  allCheck: boolean
  shopName: string
}

function getCartInfo (shop: CartShop | undefined) {
  const productList = shop?.productList
  const cart: CartInfo = {
    count: 0,
    price: 0,
    total: 0,
    allCheck: false,
    shopName: shop?.shopName || ''
  }
  if (!productList) return cart
  cart.allCheck = true
  for (const i in productList) {
    const product = productList[i] as CartProduct
    cart.total += product.count
    if (product.check) {
      cart.count += product.count
      cart.price += product.count * product.price
    } else {
      cart.allCheck = false
    }
  }
  return cart
}

/* 使用商铺购物车 */
export default function useCartEffect (shopId: string) {
  const { cartList } = appStore
  const changeCartItem = (shopName: string, product: Product, number: number) => {
    appStore.changeCartItem({
      shopId,
      shopName,
      product,
      number
    })
  }

  const cartInfo = computed<CartInfo>(() => {
    return getCartInfo(cartList[shopId])
  })

  const cartArray = computed(() => {
    const cartShop = cartList[shopId]?.productList || {}
    return Object.values(cartShop) as CartProduct[]
  })

  const purchaseCartArray = computed(() => {
    return cartArray.value.filter(product => product.check && product.count > 0)
  })

  const clearShopCart = () => {
    appStore.clearShopCart(shopId)
  }

  return {
    cartList,
    cartArray,
    purchaseCartArray,
    cartInfo,
    changeCartItem,
    clearShopCart
  }
}

/* 使用购物车 */
export function useCommonCartEffect () {
  const { cartList } = appStore
  const shopIdList = computed<string[]>(() => {
    return Object.keys(cartList)
  })

  return {
    shopIdList
  }
}
